from django.shortcuts import render

# Create your views here.
# manages/views.py
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from rest_framework import status
from rest_framework_simplejwt.tokens import RefreshToken
from .models import McManage
from .serializers import McManageSerializer
from rest_framework.permissions import IsAuthenticated
from app.common.pagination import StandardResultsSetPagination

# 查询所有用户
@api_view(["GET"])
def manage_list(request):
    items = McManage.objects.all().order_by("-created_time")
    
    # 分页
    paginator = StandardResultsSetPagination()
    result_page = paginator.paginate_queryset(items, request)
    serializer = McManageSerializer(result_page, many=True)

    return paginator.get_paginated_response(serializer.data)



# 查询单个用户
@api_view(["GET"])
def manage_detail(request, pk):
    try:
        manage = McManage.objects.get(pk=pk)
    except McManage.DoesNotExist:
        return Response({"error": "Manage not found"}, status=status.HTTP_404_NOT_FOUND)

    serializer = McManageSerializer(manage)
    return Response(serializer.data)


# 新增用户
@api_view(["POST"])
def manage_create(request):
    serializer = McManageSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


# 更新用户
@api_view(["PUT"])
def manage_update(request, pk):
    try:
        manage = McManage.objects.get(pk=pk)
    except McManage.DoesNotExist:
        return Response({"error": "Manage not found"}, status=status.HTTP_404_NOT_FOUND)

    serializer = McManageSerializer(manage, data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


# 删除用户
@api_view(["DELETE"])
def manage_delete(request, pk):
    try:
        manage = McManage.objects.get(pk=pk)
    except McManage.DoesNotExist:
        return Response({"error": "Manage not found"}, status=status.HTTP_404_NOT_FOUND)

    manage.delete()
    return Response(status=status.HTTP_204_NO_CONTENT)


# 登录用户
@api_view(["POST"])
def manage_login(request):
    user_name = request.data.get("user_name")
    password = request.data.get("password")

    if not user_name or not password:
        return Response(
            {"code": 400, "message": "用户名和密码不能为空"},
            status=status.HTTP_400_BAD_REQUEST,
        )

    try:
        user = McManage.objects.get(user_name=user_name)
    except McManage.DoesNotExist:
        return Response(
            {"code": 400, "message": "用户名或密码错误"},
            status=status.HTTP_400_BAD_REQUEST,
        )

        # 如果你存储的是明文密码
    if user.password != password:
        return Response(
            {"code": 400, "message": "用户名或密码错误"},
            status=status.HTTP_400_BAD_REQUEST,
        )

    # 生成 JWT token
    refresh = RefreshToken.for_user(
        user
    )  # DRF SimpleJWT 需要用户是 AbstractUser，如果自定义模型可手动实现 get_user_id
    access_token = str(refresh.access_token)

    serializer = McManageSerializer(user)

    response = Response(
        {"code": 200, "message": "登录成功", "user": serializer.data},
        status=status.HTTP_200_OK,
    )
    
    response['Authorization'] = f'Bearer {access_token}'

    return response
